package br.com.ufpr.util.base;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.behavior.Behavior;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.OnDomReadyHeaderItem;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.markup.repeater.RefreshingView;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.Model;

import br.com.sgp.util.handling.ErrorHandlingAjaxLink;
import br.com.ufpr.sgp.HomePage;
import br.com.ufpr.sgp.WicketApplication;
import br.com.ufpr.sgp.components.MenuItem;
import br.com.ufpr.sgp.components.MenuItemPanel;
import br.com.ufpr.sgp.components.MenuItemSubmenuPanel;
import br.com.ufpr.sgp.pages.LogoutPage;
import br.com.ufpr.sgp.pages.ModalAlterarDadosPessoais;
import br.com.ufpr.sgp.pages.ModalAlterarSenha;
import br.com.ufpr.sgp.pages.processo.ConsultarProcessoPage;
import br.com.ufpr.sgp.util.session.CustomSession;

/**
 * Página base das páginas que implementem o layout padrão da aplicação.
 * 
 * @author Willian Tanaka
 */
public class BaseLayoutPage extends BasePage {
	private static final long serialVersionUID = 2048582950380637195L;

	public static final Logger log = Logger.getLogger(BaseLayoutPage.class);

	private static final String NME_CLASS_SELECTOR_TOOLTIP = "showTooltip";

	private IModel<String> pageTitle;

	public BaseLayoutPage(final IModel<String> pageTitle) {
		super();
		this.pageTitle = pageTitle;
		loadBaseLayoutPage();
	}

	private void loadBaseLayoutPage() {

		final Label lblNmeUsu = new Label("nmeUsuarioLogado",
				new LoadableDetachableModel<String>() {
					private static final long serialVersionUID = -3746363453836223746L;

					@Override
					protected String load() {
						return CustomSession.get().getUsuario()
								.getNomeUsuario();
					}
				});
		lblNmeUsu.setOutputMarkupId(true);
		add(lblNmeUsu);

		final ModalAlterarSenha modalAlterarSenha = new ModalAlterarSenha(
				"modalAlterarSenha", BaseLayoutPage.this.getPageReference()) {
			private static final long serialVersionUID = -4730314120016422422L;

			@Override
			public void onClose(AjaxRequestTarget target) {
				atualizarFeedbackPanel(target);
			}
		};
		add(modalAlterarSenha);

		final ModalAlterarDadosPessoais modalAlterarDadosPessoais = new ModalAlterarDadosPessoais(
				"modalAlterarDadosPessoais",
				BaseLayoutPage.this.getPageReference()) {
			private static final long serialVersionUID = -528058225629171379L;

			@Override
			public void onClose(AjaxRequestTarget target) {
				atualizarFeedbackPanel(target);
				target.add(lblNmeUsu);
			}
		};
		add(modalAlterarDadosPessoais);

		final Label pageTitleLbl = new Label("pageTitle",
				new LoadableDetachableModel<String>() {
					private static final long serialVersionUID = -3746363453836223746L;

					@Override
					protected String load() {
						return new Model("SGP ").getObject()
								+ " - "
								+ (pageTitle != null ? pageTitle
										: getPageTitle()).getObject();
					}
				});
		pageTitleLbl.setRenderBodyOnly(true);
		add(pageTitleLbl);

		montaMenu();

		/*
		 * final PageParameters pp = new PageParameters(); pp.add("minhasSmps",
		 * "true"); add(new Link<IndexPage>("lnkMinhasSmps") { private static
		 * final long serialVersionUID = 1038857339679130654L;
		 * 
		 * @Override public void onClick() { final IModel<SmpDto> smpModel =
		 * ModelFactory.getSmpModel();
		 * smpModel.getObject().setResponsavel(CustomSession
		 * .get().getUsuario()); setResponsePage(new IndexPage(smpModel)); } });
		 */
		final BookmarkablePageLink<?> lnkIndex = new BookmarkablePageLink<BasePage>(
				"lnkIndex", WicketApplication.get().getHomePage());
		lnkIndex.add(new Label("lblLnkIndex", new Model("SGP")));
		add(lnkIndex);

		add(new ErrorHandlingAjaxLink("lnkAlterarDadosPessoais") {
			private static final long serialVersionUID = -810613255291378504L;

			@Override
			public void onClicked(AjaxRequestTarget target) {
				modalAlterarDadosPessoais.show(target);
			}

		});

		add(new ErrorHandlingAjaxLink("lnkAlterarSenha") {
			private static final long serialVersionUID = -4781011284897078240L;

			@Override
			public void onClicked(AjaxRequestTarget target) {
				modalAlterarSenha.show(target);
			}

		});

		add(new BookmarkablePageLink<LogoutPage>("lnkLogout", LogoutPage.class));

		add(new Behavior() {
			private static final long serialVersionUID = 7123763355895720820L;

			@Override
			public void renderHead(Component component, IHeaderResponse response) {
				response.render(OnDomReadyHeaderItem.forScript("$('."
						+ NME_CLASS_SELECTOR_TOOLTIP + "').tooltip()"));
			}

		});

	}

	private void montaMenu() {
		final List<IModel<MenuItem>> menuItemsLabels = new ArrayList<IModel<MenuItem>>();
		menuItemsLabels.add(new MenuItem(new Model<String>("Pesquisar Processos"),
				ConsultarProcessoPage.class));

		if (CustomSession.get().getUsuario().isAdmin()) {
			final MenuItem desenvolvedor = new MenuItem(new Model<String>(
					"Desenvolvedor"));
			desenvolvedor.addSubmenu(new MenuItem(new Model<String>(
					"Verificar Arquivos da SMP"), HomePage.class));
			menuItemsLabels.add(desenvolvedor);
		}

		final RefreshingView<MenuItem> view = new RefreshingView<MenuItem>(
				"menuList") {
			private static final long serialVersionUID = 273638454211475848L;

			@Override
			protected Iterator<IModel<MenuItem>> getItemModels() {
				return menuItemsLabels.iterator();
			}

			@Override
			protected void populateItem(final Item<MenuItem> item) {
				if (item.getModelObject().getClazz() != null) {
					item.add(new MenuItemPanel("panel", item.getModelObject()));

				} else {
					item.add(new MenuItemSubmenuPanel("panel", item
							.getModelObject(), BaseLayoutPage.this.getClass()));
				}

				if (item.getModelObject().isUmDosSubMenusAtivos(
						BaseLayoutPage.this.getClass())) {
					item.add(AttributeModifier.replace("class", "active"));
				}
			}
		};

		add(view);
	}

	public static void addTooltip(final Component c, final String tooltip) {
		c.add(AttributeModifier.replace("data-toggle", "tooltip"));
		c.add(AttributeModifier.replace("title", tooltip));
		c.add(AttributeModifier.append("class", NME_CLASS_SELECTOR_TOOLTIP));
	}

	/**
	 * Obtém o título da página, chamado somente quando o título da página não
	 * for passado ao construtor.
	 * 
	 * @return
	 */
	protected IModel<String> getPageTitle() {
		throw new IllegalArgumentException(
				"BaseLayoutPage.getPageTitle() deve ser implementado quando o pageTitle não for passado ao construtor da BaseLayoutPage!");
	}

}
